<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 合同
 *
 */
class XContract extends Backend
{
    /**
     * XContract模型对象
     * @var \app\admin\model\XContract
     */
    protected $model = null;
    
    protected $quickSearchField = ['id'];

    protected $defaultSortField = 'id,desc';

    protected $preExcludeFields = [''];
    protected $noNeedLogin      = ['*'];
    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\XContract;
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $wheres='';
        $crop=$this->request->get('CORP');
        $type=$this->request->get('type');
        $types='';
        if($type==1){
            $types=['companytype'=>'客户'];
        }elseif($type==2){
            $types=['companytype'=>'供应商'];
        }
        if($crop){
            $wheres=['CORP'=>$crop,'ACTIVE'=>1];
        }
        $adminInfo          = $this->auth->getInfo();
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $sy_type=$this->request->get('code');
        if($sy_type && $sy_type='KHHT'){
            $res = $this->model
                ->field('x_contract.*,DEPARTMENT.DEPTNAME')
                ->alias($alias)
                ->join('corplib',"corplib.corp=x_contract.corp")
                ->join('DEPARTMENT',"x_contract.DEPT=DEPARTMENT.DEPTID",'left')
                ->where($where)
                ->where("corplib.companytype='客户' and datediff(day,getdate(),x_contract.enddate)<(select isnull(max(CAST(attr as int)),0) from codelib where code='KHHT' and codetype='alarmsetup' ) and  (corplib.pflag='1' or exists (select * from admin where CHARINDEX(corplib.DEPT,admin.department)>0 and admin.username='$adminInfo[username]'))")
                ->where($types)
                ->order($order)
                ->paginate($limit);
        }else{
            $res = $this->model
                ->field('x_contract.*,DEPARTMENT.DEPTNAME')
                ->withJoin($this->withJoinTable, $this->withJoinType)
                ->join('DEPARTMENT',"x_contract.DEPT=DEPARTMENT.DEPTID",'left')
                ->join('corplib',"corplib.corp=x_contract.corp",'left')
                ->alias($alias)
                ->where($where)
                ->where($wheres)
                ->where($types)
                ->order($order)
//                ->fetchSql()->select();
                ->paginate($limit);
        }

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 添加
     */
    public function add()
    {


        if ($this->request->isPost()) {

            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $adminInfo          = $this->auth->getInfo();
            $data['OPNAME']=$adminInfo['nickname'];
            $data['OPDATETIME']=date('Y-m-d H:i:s',time());
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }
        $this->error(__('Parameter error'));
    }
    /**
     * 编辑
     */
    public function edit()
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }
        $this->success('', [
            'row' => $row
        ]);
    }
}